package com.xm.servlet.reception_desk.center;

import com.xm.entity.AccountInformation;
import com.xm.entity.Address;
import com.xm.entity.Coupons;
import com.xm.entity.Orders;
import com.xm.exception.SqlErrorException;
import com.xm.service.reception_desk.AccountInformationService;
import com.xm.service.reception_desk.AddressService;
import com.xm.service.reception_desk.CouponsService;
import com.xm.service.reception_desk.OrdersService;
import com.xm.util.DecryptExampleUtil;
import lombok.SneakyThrows;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.net.URLEncoder;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

/**
 * @author 田顺琪
 * @date 2023-12-29 上午11:28
 */
@WebServlet(name = "CenterServlet", value = "/center")
public class CenterServlet extends HttpServlet {
    /**
     * 地址service
     */
    private final AddressService addressService=new AddressService();
    /**
     * 优惠卷service
     */
    private final CouponsService couponsService=new CouponsService();
    /**
     * 用户账号信息service
     */
    private final AccountInformationService accountInformationService=new AccountInformationService();
    /**
     * 订单service
     */
    private final OrdersService ordersService=new OrdersService();
    @SneakyThrows(Exception.class)
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
        //获取所有参数 并且封装在Map集合
        Map<String, String[]> parameterMap = req.getParameterMap();
        HttpSession session = req.getSession(false);
        // 获取会话中存储的CSRF令牌
        String sessionToken = null;
        try {
            sessionToken = (String) session.getAttribute("token");
        }catch (Exception e){
            System.out.println("没有登陆");
        }
        //AES解密
        String informationId = DecryptExampleUtil.decrypt(parameterMap.get("informationId")[0]);
        System.out.println("解密结果：" + informationId);
        // 验证CSRF令牌
        if (sessionToken != null) {
            //账户ID
            req.setAttribute("accountId", parameterMap.get("accountId")[0]);
            req.setAttribute("name", parameterMap.get("name")[0]);
            req.setAttribute("id",Integer.parseInt(informationId));
            System.out.println(parameterMap.get("informationId")[0]);
            req.setAttribute("notDecryptedInformationId", URLEncoder.encode(parameterMap.get("informationId")[0], "UTF-8").replace("+", "%2B").replace("=", "%3D"));
            //菜单
            String menu = req.getParameter("menu") == null ?  "3" : req.getParameter("menu");
            req.setAttribute("menu",menu);
            // 令牌失效
            req.setAttribute("status", true);
            //地址
            String addressMenu="6";
            //订单
            String orderMenu = "1";
            String orderDetailsMenu = "11";

            //评价晒当
            String appraiseMenu="2";
            //个人中心
            String personalMenu="3";
            if(menu.equals(personalMenu)){
                addAccountInformation(req,Integer.parseInt(informationId),Integer.parseInt(parameterMap.get("accountId")[0]));
            }
            //消息通知
            String noticesMenu="4";
            //优惠卷
            String couponsMenu="5";
            if(menu.equals(couponsMenu)){
                int state = req.getParameter("state")==null ? 0 : Integer.parseInt(req.getParameter("state"));
                addCoupons(req,Integer.parseInt(informationId),state);
            }
            if(menu.equals(addressMenu)){
                //地址
                addAddress(req,Integer.parseInt(informationId));
            }else if (menu.equals(orderMenu)){
                //订单
                String status=req.getParameter("status");
                String searchInput=req.getParameter("searchInput");
                String ordersId=req.getParameter("ordersId");
                if(ordersId!=null){
                    ordersDelete(req,Integer.parseInt(informationId),ordersId,status,searchInput);
                }else {
                    orderMenu(req,Integer.parseInt(informationId),status,searchInput);
                }
            }else if (menu.equals(orderDetailsMenu)){
                //订单详情
                List<Orders> orders=ordersService.getOrdersDetails(Integer.parseInt(informationId),req.getParameter("ordersId"));
                orders.forEach(System.out::println);
                req.setAttribute("orders",orders);
            }
            req.getRequestDispatcher("/WEB-INF/page/reception_desk/center.jsp").forward(req,resp);
        }else{

            //没有登陆
            req.setAttribute("menu",0);
            req.getRequestDispatcher("/WEB-INF/page/reception_desk/login.jsp").forward(req,resp);
        }
    }

    private void ordersDelete(HttpServletRequest req, Integer informationId, String ordersId,String status,String searchInput) throws SqlErrorException {
        //订单删除
        boolean ret=ordersService.getOrderDelete(informationId,ordersId);
        if (ret){
            orderMenu(req,informationId,status,searchInput);
        }
    }

    @SneakyThrows
    public void orderMenu(HttpServletRequest req, Integer informationId,String status,String searchInput){
        //查询用户订单
        List<Orders> ordersByInformationId = ordersService.getOrdersByInformationId(informationId,status,searchInput);
        ordersByInformationId.forEach(System.out::println);
        req.setAttribute("orders",ordersByInformationId);
        req.setAttribute("state",status);
    }
    private void addCoupons(HttpServletRequest req, int id,int state) throws SQLException {
        List<Coupons> coupons=couponsService.getAvailableCouponsByInformationId(id,state);
        int unusedCount = couponsService.couponsCount(id,0);
        int usedCount = couponsService.couponsCount(id,1);
        int expiredCount = couponsService.couponsCount(id,2);
        //默认显示主页
        req.setAttribute("state",state);
        req.setAttribute("coupons", coupons);
        req.setAttribute("usedCount", usedCount);
        req.setAttribute("unusedCount", unusedCount);
        req.setAttribute("expiredCount", expiredCount);
    }


    public void addAddress(HttpServletRequest req ,Integer id) throws SqlErrorException {
        List<Address> address = addressService.getAllAddresses(id);
        //默认显示主页
        req.setAttribute("address", address);
    }

    public void addAccountInformation(HttpServletRequest req ,Integer id,Integer accountId) throws SqlErrorException {
        AccountInformation accountInformation=accountInformationService.getPersonalCenter(id);
        //未支付
        int unpaid=0;
        //未发货
        int notShipped=0;
        //未评论
        int noComment=0;
        //最大循环数
        int maxCount=10;
        for (int i = 0; i < maxCount; i++) {
            if(i==0){
                unpaid += ordersService.getOrderCount(id,i);
            }else if(i>=4 && i<9){
                notShipped += ordersService.getOrderCount(id,i);
            } else if (i==9) {
                noComment += ordersService.getOrderCount(id,i);
            }
        }
        //默认显示主页
        req.setAttribute("accountInformation", accountInformation);
        req.setAttribute("unpaid", unpaid);
        req.setAttribute("notShipped", notShipped);
        req.setAttribute("noComment", noComment);
    }

}
